package com.pansoft.espcomp.esplistview;

import java.util.Calendar;

import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;

/**
 * 管理ListView的上次刷新时间
 * @author zhangjg
 * 2013 12 17
 */
public class LastRefreshTime {
	
	private static final String LAST_REFRESH_SP_NAME = "last_refresh";
	private static final String LAST_REFRESH_KEY = "last_refresh_time";
	
	/**
	 * 保存上次刷新时间, 在每次刷新完成时调用
	 * @param context
	 */
	public static void setLastRefresh(Context context){
		
		StringBuilder sb = new StringBuilder();
		
		Calendar ca = Calendar.getInstance();
		int month = ca.get(Calendar.MONTH) + 1;
		int day = ca.get(Calendar.DAY_OF_MONTH);
		int hour = ca.get(Calendar.HOUR_OF_DAY);
		int min = ca.get(Calendar.MINUTE);
		

		String minStr = min < 10 ? "0" + String.valueOf(min) : String.valueOf(min);
		
		//格式   "9月5日 16:34" 
		String msg = sb.append(String.valueOf(month)).append("月")
				.append(String.valueOf(day)).append("日").append(" ")
				.append(String.valueOf(hour)).append(":").append(minStr)
				.toString();
		
		SharedPreferences sp = context.getSharedPreferences(LAST_REFRESH_SP_NAME, Context.MODE_PRIVATE);
		Editor  editor = sp.edit();
		editor.putString(LAST_REFRESH_KEY, msg);
		
		editor.commit();
		
	}
	
	/**
	 * 显示上次刷新时间, 在下拉时调用
	 * 格式   "上次刷新时间: 9月5日 16:34"  或         "上次刷新时间: 今天 16:34" 	或 	""
	 * @param context
	 * @return
	 */
	public static String getLastRefresh(Context context){
		
		SharedPreferences sp = context.getSharedPreferences(LAST_REFRESH_SP_NAME, Context.MODE_PRIVATE);
		String last = sp.getString(LAST_REFRESH_KEY, "");
		
		if("".equals(last)){
			return "";
		}
		
		//格式   "9月5日 16:34"  或         "今天 16:34" 
		StringBuilder sb = new StringBuilder("上次刷新时间: ");
		
		
		Calendar nowCa = Calendar.getInstance();
		int month = nowCa.get(Calendar.MONTH) + 1;
		int day = nowCa.get(Calendar.DAY_OF_MONTH);
//		int hour = nowCa.get(Calendar.HOUR_OF_DAY);
//		int min = nowCa.get(Calendar.MINUTE);
		
		String lastMonth = last.split("月")[0];        //9
		
		String withoutMonth = last.split("月")[1];     //5日 16:34
		
		String lastDay = withoutMonth.split("日")[0];   //5
		
		String lastTime = last.split(" ")[1]; 				//16:34
		
		boolean today = lastMonth.equals(String.valueOf(month)) && lastDay.equals(String.valueOf(day));
		if(today){
			sb.append("今天").append(" ").append(lastTime);
			return sb.toString();
		}
		
		
		return sb.append(last).toString();
	}
}
